package handler

import (
	"github.com/gin-gonic/gin"
	"order-exam/model"
	"strconv"
)

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserAndRole(c *gin.Context) {
	uid := c.Query("uid")
	/*
	   SELECT
	   *
	   FROM
	   roles
	   LEFT JOIN user_roles ON user_roles.rid=roles.id
	   WHERE
	   user_roles.uid=1
	*/
	var role []model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).
		Debug().
		Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
}

func RoleAndNode(c *gin.Context) {
	nid := c.Query("nid")
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON role_nodes.rid=nodes.id
		WHERE
		role_nodes.nid=1
	*/
	var node []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.rid=nodes.id").
		Where("role_nodes.nid=?", nid).
		Debug().
		Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
}
